package com.jihox.abookpro;

import java.io.File;
import java.util.Properties;
import java.util.Stack;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.jihox.abookpro.dao.BookProjectDAO;
import com.jihox.abookpro.domain.BookProduct;
import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.BookTemplate;
import com.jihox.abookpro.domain.Page;
import com.jihox.abookpro.domain.PagePicture;

public class MyApplication extends Application implements Thread.UncaughtExceptionHandler{
	private static Stack<Activity> activityStack;
    private static MyApplication singleton;
    private final String USER_NAMESPACE			=	"USERINFO";
    private final String USER_IDCODE			=	"USERIDCODE";
//    private final String CUSTOMERCODE_NAME		=	"CUSTOMERCODE";
    private static final String SHAREDPREFERENCES_CUSTOMERINFO = "CUSTOMER_TOKEN";
    //程序异常处理
    private MyUncaughtExceptionHandler UncaughtExceptionHandler;
    private BookProduct bookProduct;
    private BookProject bookProject;
    private String worksn;
    private boolean sendErrorMail = true;
    private static final String projectFileName = "savedProject.xml";
    private String cstToken;
    private String templateName;
    private String user_Id_Code;
    private BookTemplate template;
    
    
    
    
	public BookTemplate getTemplate() {
		return template;
	}

	public void setTemplate(BookTemplate template) {
		this.template = template;
	}

	public String getUserId() {
		if(user_Id_Code == null){
			//查询用户userid
			SharedPreferences preferencesToken = getSharedPreferences(
					USER_IDCODE, MODE_PRIVATE);
			user_Id_Code = preferencesToken.getString("user_Id_Code", "").toString();
		}
		return user_Id_Code;
	}

	public void setUserId(String userIdCode) {
		//获取userid					
		SharedPreferences preferences = getSharedPreferences(
				USER_IDCODE, Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		// 保存userid
		editor.putString("user_Id_Code", userIdCode);
		// 提交修改
		editor.commit();		
		this.user_Id_Code = userIdCode;
	}

	public String getTemplateName() {
		if (templateName ==null){
			templateName = getProperty("templateName");
		}
		return templateName;
	}

	public void setTemplateName(final String templateName) {
		this.templateName = templateName;
		//将登录信息序列化
		setProperties(new Properties(){
		{
			setProperty("templateName", templateName);

		}});
	}

	public String getCstToken() {
		if(cstToken == null){
			//查询用户cstToken
			SharedPreferences preferencesToken = getSharedPreferences(
					SHAREDPREFERENCES_CUSTOMERINFO, MODE_PRIVATE);
			cstToken = preferencesToken.getString("cstToken", "").toString();
		}
		return cstToken;
	}

	public void setCstToken(String cstToken) {
		//获取cstToken					
		SharedPreferences preferences = getSharedPreferences(
				SHAREDPREFERENCES_CUSTOMERINFO, Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		// 保存cstToken
		editor.putString("cstToken", cstToken);
		// 提交修改
		editor.commit();
		
		this.cstToken = cstToken;
	}

	public String getWorksn() {
		if (worksn ==null){
			worksn = getProperty("worksn");
		}
		return worksn;
	}

	public BookProject getBookProject() {
		if (bookProject ==null){
			BookProjectDAO dao = new BookProjectDAO();
			try {
				bookProject = dao.retrieveBookProject( getCacheDir() + "/" + projectFileName);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bookProject;
	}

	public void setBookProject(BookProject project) {
		this.bookProject = project;
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					BookProjectDAO dao = new BookProjectDAO();
					dao.saveProject(bookProject, getCacheDir() + "/" + projectFileName);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public void setWorksn(final String worksn) {
		this.worksn = worksn;
		//将登录信息序列化
		setProperties(new Properties(){
		{
			setProperty("worksn", worksn);

		}});	
	}

	public boolean isSendErrorMail() {
		return sendErrorMail;
	}

	public void setSendErrorMail(boolean sendErrorMail) {
		this.sendErrorMail = sendErrorMail;
	}

	public BookProduct getBookProduct() {
		return bookProduct;
	}
    
	public void setBookProduct(BookProduct bookProduct) {
		this.bookProduct = bookProduct;
	}
	
	public void setProperties(Properties ps){
		AppConfig.getAppConfig(this).set(ps);
	}

	public String getProperty(String key){
		return AppConfig.getAppConfig(this).get(key);
	}
	
	@Override
    public void onCreate()
    {
        super.onCreate();
        singleton=this;
        //初始化异常处理器
        UncaughtExceptionHandler=MyUncaughtExceptionHandler.getInstance();
        UncaughtExceptionHandler.init(getApplicationContext());
        //初始化TuSDK
//        TuSdk.enableDebugLog(true);//Log调试
//        TuSdk.init(this.getApplicationContext(), "6cd6e8bc6d80d3cc-00-qo9un1");
        
//        TuSdk.init(this.getApplicationContext(), "a192136b2dc52105-01-qo9un1");
       
//        TuSdk.init(this.getApplicationContext(), "b03f9b9b33f0e6de-01-qo9un1");

    }
    // Returns the application instance
    public static MyApplication getInstance() {
        return singleton;
    }

    /**
     * add Activity 添加Activity到栈
     */
    public void addActivity(Activity activity){
        if(activityStack ==null){
            activityStack =new Stack<Activity>();
        }
        
        activityStack.add(activity);
    }
    /**
     * get current Activity 获取当前Activity（栈中最后一个压入的）
     */
    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }
    /**
     * 结束当前Activity（栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
                
            }
        }
        activityStack.clear();
    }
    
    @Override  
    public void onTerminate() {  
    	super.onTerminate();
        finishAllActivity();
        Intent intent = new Intent();
		ComponentName cn = new ComponentName(this, "com.jihox.abookpro.uploader.UploadService");  
		intent.setComponent(cn);
        getApplicationContext().stopService(intent);
        
       // System.exit(0);
    }
	@Override
	public void uncaughtException(Thread arg0, Throwable arg1) {
		// TODO Auto-generated method stub
	}  
	
	
	
	/**
	 * 判断bookProject的图片是否存在
	 * @param bookProject
	 * @return page null 全部存在， 不为null，有不存在的图片。
	 */
	public Page checkImageExist(BookProject bookProject)
	{
		for(Page currentPage : bookProject.getBook().getPages()){
			if(currentPage.getPictures() != null && currentPage.getPictures().size() > 0){
				for(PagePicture pagePicture : currentPage.getPictures()){
					if(!pagePicture.isClipart()){
						String path = pagePicture.getImage().getPath();
						File file = new File(path);
						if(!file.exists()){
							return currentPage;
						}
					}
				}
			}
		}
		return null;
	}
}
